import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/top-nav',
      name: 'top-nav',
      redirect: '/home',
      component: () => import('@/components/TopNavigation.vue'),
      children: [
        {
          path: '/home',
          name: 'home',
          component: HomeView,
        },
        {
          path: '/battle',
          name: 'battle',
          component: () => import('@/views/BattleView.vue'),
        },
        {
          path: '/theme',
          name: 'theme',
          component: () => import('@/views/ThemeView.vue'),
        },
        {
          path: '/user',
          name: 'user',
          component: () => import('@/views/UserView.vue'),
        },
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    },
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 假设 token 存在 localStorage 中
  const isAuthenticated = !!localStorage.getItem('token')
  console.log('isAuthenticated', isAuthenticated)

  // 如果没登录且目标不是登录页，跳转登录
  if (!isAuthenticated && to.path !== '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})

export default router
